﻿using Assets.Scripts.DL.Consts;
using Assets.Scripts.DL.Mgrs;
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem.XR;

public class PlayerSlide : PlayerBaseState {
	bool _isSlideStop;
	bool _canExit;
	readonly Timer _timer;
	Timer _makeShadowGap = new();
	bool _overAnimStart;
	bool _setVelocityZero;
	public PlayerSlide(PlayerController controller, PlayerStateEnum stateName, State<PlayerStateEnum> superFSM, StateFactory<PlayerStateEnum> factory) : base(controller, stateName, superFSM, factory) {
		_timer = new Timer();
		AddConditionToSelf(() => false);

		AddNewTransition(PlayerStateEnum.Crouch, () => _canExit && _controller.IsTouchCeiling);
		AddNewTransition(PlayerStateEnum.Run, () => _canExit && !controller.IsTouchCeiling && !_controller.WalkInput);
		AddNewTransition(PlayerStateEnum.Walk, () => _canExit && _controller.WalkInput);
	}

	public override void Enter() {
		AudioManager.Play(_controller.StateAudio, AudioStr.PlayerSlideAudio);
		var speed = _controller.ConfigData.SlideSpeed;
		var dir = _controller.XInput;
		_controller.Velocity = new Vector2(speed * dir, 0);
		_timer.Reset();
		_canExit = false;
		_isSlideStop = false;
		_setVelocityZero = false;
		//var decayAmount = Time.deltaTime / Controller.ConfigData.SlideTime * speed;

		//_decay = new Vector2(-dir * decayAmount, 0);
		_controller.PlayAnim(PlayerStateEnum.SlideLoop);
		_controller.UpColl.enabled = false;
		_overAnimStart = false;
		_controller.StateData.CanChangeDir = false;
		_makeShadowGap.Reset();
	}

	public override void Exit() {
		//Controller.SetVelocity(new Vector2(0, 0));
		_controller.StateData.CanChangeDir = true;
		_controller.UpColl.enabled = true;
	}

	public override void Update() {
		base.Update();
		//Controller.IsAnimPlayOver();
		_controller.MakeShadowSyn(_makeShadowGap, _controller.ConfigData.ShadowGap);

		if (_timer.Elapsed > _controller.ConfigData.SlideTime) {
			_isSlideStop = true;
			if (!_setVelocityZero) {
				_controller.Velocity = Vector2.zero;
				_setVelocityZero = true;
			}
			bool tmp = true;
			if (_isSlideStop) {
				if (!_overAnimStart) {
					_controller.PlayAnim(PlayerStateEnum.SlideOver);
					//Debug.Log("1");
					_overAnimStart = true;
					tmp = false;
				}
				if (tmp && _controller.IsAnimPlayOver()) {
					_canExit = true;
				}
			}
		}
	}
}